package ${package.ServiceImpl};

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.beans.response.PageResponse;
import ${package.Bo}.${BoName};
import ${package.Entity}.${entity};
import ${package.Query}.${QueryName};
import ${package.QueryRequest}.${QueryRequestName};
import ${package.QueryResponse}.${QueryResponseName};
import ${package.Convertor}.${ConvertorName};
import ${package.Manager}.${ManagerName};
import ${package.Service}.${ServiceName};
import com.pine.service.util.PageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * ${table.comment!} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Service
public class ${ServiceImplName} implements ${ServiceName} {

    @Resource
    private ${ManagerName} ${entityLowerCaseFirstOne}Manager;

    @Resource
    private ${ConvertorName} ${entityLowerCaseFirstOne}Convertor;

    private static final Map<${stringStr}, SFunction<${EntityName}, ?>> COLUMNS_FUNCTION_MAP;
    static {
        COLUMNS_FUNCTION_MAP = Map.of(
            "${primaryKeyName}", ${EntityName}::get${primaryKeyNameUpperCaseFirstOne}
        );
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public ${QueryResponseName} getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        ${BoName} ${entityLowerCaseFirstOne}Bo = ${entityLowerCaseFirstOne}Manager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, ${EntityName}::get${primaryKeyNameUpperCaseFirstOne}));
        return ${entityLowerCaseFirstOne}Convertor.entityBoToQueryResponse(${entityLowerCaseFirstOne}Bo);
    }


    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<${QueryResponseName}> list(${QueryRequestName} request) {
        ${EntityName}Query ${entityLowerCaseFirstOne}Query = ${entityLowerCaseFirstOne}Convertor.queryRequestToQuery(request);
        if (ObjectUtil.isNotEmpty(${entityLowerCaseFirstOne}Query)) {
            List<${BoName}> ${entityLowerCaseFirstOne}List = ${entityLowerCaseFirstOne}Manager.list(${entityLowerCaseFirstOne}Query);
            if (ObjectUtil.isNotEmpty(${entityLowerCaseFirstOne}List)) {
                return ${entityLowerCaseFirstOne}List.stream()
                    .map(${entityLowerCaseFirstOne}Convertor::entityBoToQueryResponse)
                    .filter(ObjectUtil::isNotEmpty)
                    .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
    * 查询信息（分页）
    *
    * @param request 请求
    * @return PageResponse 响应
    */
    @Override
    public PageResponse<${QueryResponseName}> listPages(PageRequest<${QueryRequestName}> request) {
        try {
            // 分页查询
            IPage<${BoName}> ${entityLowerCaseFirstOne}Page = ${entityLowerCaseFirstOne}Manager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(${entityLowerCaseFirstOne}Page);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param ${entityLowerCaseFirstOne}Page 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<${QueryResponseName}> safelyConvertPage(IPage<${BoName}> ${entityLowerCaseFirstOne}Page) {
        if (${entityLowerCaseFirstOne}Page == null || CollUtil.isEmpty(${entityLowerCaseFirstOne}Page.getRecords())) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<${QueryResponseName}> responses = ${entityLowerCaseFirstOne}Page.getRecords().parallelStream()
            .map(${entityLowerCaseFirstOne}Bo -> ${entityLowerCaseFirstOne}Convertor.entityBoToQueryResponse(${entityLowerCaseFirstOne}Bo))
            .collect(Collectors.toList());

        return PageUtil.convertPage(${entityLowerCaseFirstOne}Page, responses);
    }


    /**
    * 将请求 request 转换成 manager 的 query 对象
    *
    * @param request 请求参数
    * @return query 对象
    */
    private PageRequest<${QueryName}> transformToQuery(PageRequest<${QueryRequestName}> request) {
        ${QueryName} ${entityLowerCaseFirstOne}Query = ${entityLowerCaseFirstOne}Convertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), ${entityLowerCaseFirstOne}Query);
    }
}
